<template>
	<view class="ss">
		<view class="tupian" v-if="!editing">
				<image  class="responsive-image" :src="imgUrl"></image>
		</view>
	<view class="zhuti">
		<view v-for="(item, index) in [xx]" :key="index" class="zhuti_01">
		      <view class="biaoti">
				  <view v-if="editing">
					  <text>修改商品封面</text>
					  <view class="pic" @click="chooseImage()">
					  	<img :src="imgUrl" class="xiugaitupian" />
					  </view>
				  </view>
		        <text v-if="!editing" style="font-weight: bold; font-size: 20px;">{{item.goodsName}}</text>
		       <uni-easyinput v-else v-model="item.goodsName" class="edit-input" @blur="validateTitle('goodsName')"/>
		      </view>
		      <view class="danwei">
		        <text style="font-weight: lighter;">商品分类:</text>
				
			<uni-data-select
			 v-if="editing"
			        v-model="value01"
			        :localdata="range"
			        @change="change"
			      ></uni-data-select>
				  
			<text v-else class="danwei">{{ item.tname }}</text>
		      </view>
		      <view class="pinzhong">
		        <text style="font-weight: lighter;">商品品种:</text>
				<text v-if="!editing"></text>
		        <uni-easyinput v-else v-model="item.varietys" class="edit-input" @blur="validateTitle('varietys')"/>
		        <text v-if="!editing" class="pinzhong">{{item.varietys}}</text>
		      </view>
			  <view class="danwei">
			    <text style="font-weight: lighter;">商品单位:</text>

			  	<uni-data-select
			  	 v-if="editing"
			  	        v-model="value"
			  	        :localdata="rangedanwei"
			  	        @change="change01"
			  	      ></uni-data-select>
				
			    <text v-if="!editing" class="danwei">{{item.unitName}}</text>
			  </view>
			  <view class="fenlei">
			    <text style="font-weight: lighter;">商品价格:</text>
			  				<text v-if="!editing"></text>
			    <uni-easyinput v-else v-model="price" class="edit-input" @blur="validateTitle('price')"/>
			    <text v-if="!editing" class="fenlei">￥{{price}}</text>
			  </view>
		      <view class="jianjie">
		        <text style="font-weight: lighter;">商品简介:</text>
				<text v-if="!editing"></text>
		        <uni-easyinput v-else v-model="item.introduces"  class="edit-input" @blur="validateTitle('introduces')"/>
		        <text v-if="!editing" class="jianjie">{{item.introduces}}</text>
		      </view>
			  
			  
			  
			  
			  <view class="anniu">
		      <button v-if="!editing" @click="editItem(index)" class="xiugai">修改</button>
			  <button v-if="!editing"  @click="shanchu(index)" class="shanchu">删除</button>
		      <button v-if="editing" @click="saveItem(item)" class="baocun">保存</button>
		      <button v-if="editing" @click="cancelEdit(index)" class="quxiao">取消</button>
		    </view>
		    </view>
			
		    
			
	</view>
	</view>
	<!-- 删除 -->
			<view v-if="showDialog" class="dialog">
			      <view class="dialog-content">
					  <view>
						  <text>确定要删除吗？</text>
					  </view>
					<view class="qrenshanchu">
						<button class="handleConfirm" style="width: 100rpx; height: 60rpx; font-size: 10px;" @click="handleConfirm">确认</button>
			        <button class="handleCancel" style="width: 100rpx; height: 60rpx; font-size: 10px;" @click="handleCancel">取消</button>
					</view>
			        
			      </view>
			   
			  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad} from '@dcloudio/uni-app'
	import {http} from '/until/request.js'
//图片
const imgUrl=ref(null)
const imgFile = ref(null)
//价格
const price=ref('0.0')
//首页传的id,要根据这个id来查详细信息
const id=ref(null)
// 控制删除框的显示和隐藏
const showDialog = ref(false);
  const editing=ref(false)
  

  
	const xx=ref({
		categoryId:'',
		goodsName:'',
		tname:'',
		varietys:'',
		unitName:'',
		gjprices:'',
		introduces:''
	})
	
	const isValid = ref(true);
	//商品分类的下拉框
	const value01 = ref(0); 
	const range=ref([])
	
	const validationErrors=ref(null)
	//校验
	const validateTitle=(rex)=>{
		const vv = xx.value[rex];
		console.log(vv)
		const shuzi = /^\d+(\.\d+)?$/;
	  if(vv !== undefined && vv !== null &&vv!==''){
		 switch (rex) {
	    case 'goodsName':
	      isValid.value = vv.trim() !== '';
	      break;
	    case 'varietys':
	      isValid.value = vv.trim() !== '';
	      break;
	    case 'introduces':
	      isValid.value = vv.trim() !== '';
	      break;
	    case 'price':
	      isValid.value = shuzi.test(vv);
	      break;
	    default:
	      isValid.value = true;
	  } 
	  }else{
		  isValid.value = false;
	  }
	  if (!isValid.value) {
	      const chineseLabels = {
	        goodsName: '商品名称',
	        price: '价格',
			varietys:'商品品种',
			introduces:'商品简介'
	      };
	      const label = chineseLabels[rex] || rex;
	     if (rex === 'price') {
			  validationErrors[rex] = `${label} 必须是一个有效的数字`;
	         
	         } else {
				  validationErrors[rex] = `${label} 不能为空`;
	           
	         }
	      uni.showToast({
	        title:validationErrors[rex],
	        icon: 'none',
	        duration: 2000
	      });
	    } else {
	      delete validationErrors[rex];
	    }}
	
	
	
	//商品单位的下拉框
	const value = ref(0); 
	const rangedanwei=ref([
		{value:1,text:'件'},
		{value:2,text:'公斤'}
	])
	const change=(e)=>{
		console.log(e)
		xx.value.categoryId=e
	}
	const change01=(e)=>{
		console.log(e)
		xx.value.goodsUnit=e
	}
	const editItems = ref([]);
	//拿到id对应的商品信息
	const shangpin=async()=>{
		const ll=await http({
			url:'/lft/goods/goodsid/'+id.value
		})
		xx.value=ll.data
		
		if(ll.data.goodsPics!=null && ll.data.goodsPics.length>124){
			imgUrl.value='data:image/jpeg;base64,'+ll.data.goodsPics;
		}else{
			imgUrl.value=atob(ll.data.goodsPics)
		}
		
		
	}
	const oo=ref([])
	//商品分类
	const spff=async()=>{
		const res=await http({
			url:'/lft/stypes/strpe'
		})
		
		oo.value=res.data
		console.log(oo.value)
		for(let i = 0; i < oo.value.length; i++){
			const qq=oo.value[i]
			const cc={value:qq.id,text:qq.tname}
			range.value.push(cc)
		}
		console.log(range.value)
		
	}
	//修改图片封面
	const chooseImage=()=>{
		uni.chooseImage({
		  count: 1, // 默认9, 一次可以选择的图片数量
		  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		  success: function(res) {
		    console.log('选择图片成功:', res); // 打印整个 res 对象
		
		    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
		      console.log('图片路径:', res.tempFilePaths[0]); // 打印图片路径
		      imgUrl.value = res.tempFilePaths[0];
		      imgFile.value = res.tempFiles[0];
		
		      if (res.tempFilePaths[0]) {
		        console.log('开始压缩图片'); // 打印日志，确认进入压缩图片的逻辑
		        uni.compressImage({
		          src: res.tempFilePaths[0], // 使用 tempFilePaths[0] 作为路径字符串
		          quality: 50, // 压缩质量，范围0-100，数值越大，质量越高
		          success: function(compressRes) {
		            console.log('压缩成功:', compressRes); // 打印压缩结果
		            imgUrl.value = compressRes.tempFilePath;
		            console.log('压缩后的图片路径:', imgUrl.value);
		          },
		          fail: function(compressErr) {
		            console.error('压缩失败:', compressErr);
		            uni.showToast({
		              title: '压缩失败',
		              icon: 'none',
		              duration: 2000
		            });
		          }
		        });
		      } else {
		        console.error('图片路径为空字符串');
		        uni.showToast({
		          title: '图片路径无效',
		          icon: 'none',
		          duration: 2000
		        });
		      }
		    } else {
		      console.error('没有选择图片');
		      uni.showToast({
		        title: '请选择图片',
		        icon: 'none',
		        duration: 2000
		      });
		    }
		  },
		  fail: function(err) {
		    console.error('选择图片失败:', err);
		    uni.showToast({
		      title: '选择图片失败',
		      icon: 'none',
		      duration: 2000
		    });
		  }
		});
	}
	//拿到首页传过来的id
	onLoad((qq)=>{
		id.value=qq.id
		shangpin()
		spff()
	})
	
	const editItem=(index)=>{
		editing.value=true
		console.log(xx.value)
		value01.value=xx.value.categoryId
		value.value=xx.value.goodsUnit
	}
	//修改完保存
	const saveItem=async(index)=> {
		if(xx.value.categoryId==''){
			uni.showToast({
			  title: '商品分类不能为空',
			  icon: 'none',
			  duration: 2000
			});
		}
		if(xx.value.goodsUnit==""){
			uni.showToast({
			  title: '商品单位不能为空',
			  icon: 'none',
			  duration: 2000
			});
		}
		// 校验所有字段
		Object.keys(xx.value).forEach(field => validateTitle(field));
		console.log(Object.keys(validationErrors).length)
		// 如果没有错误，则提交表单
		if (Object.keys(validationErrors).length == 5) {
			console.log(imgUrl)
		// xx.value.goodsPics=imgUrl.value
		console.log(index)
		const xiugai=xx.value
		console.log(xiugai)
		const res=await http({
			url:'/lft/goods/update',
			method:'post',
			data:xiugai
		})
		uni.uploadFile({
		  url: 'http://localhost:8080/lft/goods/updateimg/'+id.value, // 服务器的上传接口地址
		  filePath: imgUrl.value, // 图片的临时文件路径
		  name: 'file',
		  success: function(uploadRes) {
		    console.log('上传成功:', uploadRes); // 打印上传结果
		    const serverResponse = JSON.parse(uploadRes.data);
		    console.log('服务器返回:', serverResponse);
		    // 更新 imgUrl.value 为服务器返回的路径（如果需要）
		    // imgUrl.value = serverResponse.filePath;
		  },
		  fail: function(uploadErr) {
		    console.error('上传失败:', uploadErr);
		    uni.showToast({
		      title: '上传失败',
		      icon: 'none',
		      duration: 2000
		    });
		  }
		});
		console.log(res)
		if(res.code==200){
			uni.showToast({
			  title: '修改成功',
			  icon: 'success',
			  duration: 2000
			});
		}else{
			uni.showToast({
			  title: '修改失败',
			  icon: 'error',
			  duration: 2000
			});
		}
		shangpin()
		  editing.value=false
	      // 这里可以添加保存逻辑，例如发送请求更新数据
		}
		
	    }
		const cancelEdit=(index)=>{
			editing.value=false
			 // 可以在这里重置输入框的内容，如果需要的话
		}
		// 显示删除框
		const shanchu = () => {
		  showDialog.value = true;
		};
		
		// 处理确认删除的逻辑
		const handleConfirm = async() => {
		  console.log('确认删除');
		  // 在这里添加删除逻辑
		  let ll=await http({
			  url:'/lft/goods/delete/'+id.value
		  })
		  if(ll.code==200){
			  uni.showToast({
			    title: ll.data,
			    icon: 'success',
			    duration: 2000
			  });
			  uni.navigateBack({
			  	delta: 1
			  })
			  showDialog.value = false;
		  }else{
			  uni.showToast({
			    title: "删除失败",
			    icon: 'error',
			    duration: 2000
			  });
		  }
		  
		};
		
		// 处理取消删除的逻辑
		const handleCancel = () => {
		  console.log('取消删除');
		  showDialog.value = false;
		};
		
</script>

<style lang="scss" scoped>
	.ss{
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.tupian{
		width: 100%; /* 父容器的宽度 */
		  height: 500rpx; /* 父容器的高度 */
	}
	.responsive-image {
	  width: 100%;
	  height: 100%;
	}
	.zhuti{
		width: 90%;
		height: 100%;
	}
	.zhuti_01{
		width: 100%;
		display: flex;
		flex-direction: column;
	}
	.biaoti,.danwei,.fenlei,.pinzhong,.jianjie{
		 margin-top: 15px;
		 display: flex;
		 flex-direction: column;
	}
	.xiugai {
		/* 事件确定按钮 */
		background-color: #0496d9;
		color: white;
		width: 280rpx;
		
	}
	.anniu{
		
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
	.xiugai, .shanchu, .anniu button {
	     margin: 5rpx; /* 调整按钮之间的间距 */
	}
	.shanchu{
		/* 失败按钮 */
		margin-top: 100rpx;
		width: 280rpx;
		background-color: #15B54A;
		background: rgba(255, 0, 0, 0.5);
		color: #FF0000
	}
	.baocun{
				/* 已完成按钮 */
				margin-top: 100rpx;
				width: 280rpx;
				background-color: #15B54A;
				background: rgba(136, 217, 123, 0.3);
				color: #27c986
	}
	.quxiao{
		/* 失败按钮 */
		margin-top: 100rpx;
		width: 280rpx;
		background-color: #15B54A;
		background: rgba(255, 0, 0, 0.3);
		color: #FF0000
	}
	.dialog {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  background: rgba(0, 0, 0, 0.5);
	  display: flex;
	  justify-content: center;
	  align-items: center;
	}
	
	.dialog-content {
		border: 2rpx solid black;
		width: 500rpx;
	  background: white;
	  padding: 20px;
	  border-radius: 8px;
	  text-align: center;
	  display: flex;
	  flex-direction: column;
	  justify-content: space-around;
	}
	.qrenshanchu{
		display: flex;
		flex-direction: row;
		justify-content: space-around;
	}
	
	.dialog-content p {
	  margin-bottom: 10px;
	}
	
	.dialog-content button {
		
	  margin: 5px;
	  padding: 5px 10px;
	  border: none;
	  border-radius: 4px;
	  cursor: pointer;
	}
	.handleConfirm{
				background-color: #0496d9;
					color: white;
	}
	.handleCancel{
			background-color: #e23633;
			color: white;
	}
	.example-body{
		width: 100%; /* 父容器的宽度 */
		  height: 500rpx; /* 父容器的高度 */
	}
	.xiugaitupian{
		width: 100%; /* 父容器的宽度 */
		  height: 500rpx; /* 父容器的高度 */
	}
</style>
